package io.github.qifan777.server.wallet.root.service;

import cn.dev33.satoken.stp.StpUtil;
import io.github.qifan777.server.wallet.record.entity.WalletRecord;
import io.github.qifan777.server.wallet.record.entity.WalletRecordDraft;
import io.github.qifan777.server.wallet.record.repository.WalletRecordRepository;
import io.github.qifan777.server.wallet.root.entity.Wallet;
import io.github.qifan777.server.wallet.root.entity.WalletDraft;
import io.github.qifan777.server.wallet.root.repository.WalletRepository;
import io.qifan.infrastructure.common.exception.BusinessException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
@Slf4j
@AllArgsConstructor
@Transactional
public class WalletService {
    private final WalletRepository walletRepository;
    private final WalletRecordRepository walletRecordRepository;

    public WalletRecord change(WalletRecord walletRecord) {
        Wallet wallet = walletRepository.findById(StpUtil.getLoginIdAsString())
                .orElseThrow(() -> new BusinessException("钱包不存在"));
        if (wallet.balance().add(walletRecord.amount()).compareTo(BigDecimal.ZERO) < 0) {
            throw new BusinessException("余额不足");
        }
        walletRepository.save(WalletDraft.$.produce(wallet,
                draft -> {
                    draft.setBalance(draft.balance().add(walletRecord.amount()));
                }));
        return walletRecordRepository.insert(WalletRecordDraft.$
                .produce(walletRecord, draft -> draft
                        .setWalletId(StpUtil.getLoginIdAsString())
                        .setBalance(wallet.balance().add(walletRecord.amount()))));
    }
}